// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class Qrj_spine extends cc.Component {

    @property
    auto_removeSelf: boolean = false;

    @property([String])
    animation: String[] = [];

    sp: sp.Skeleton = null;
    onLoad() {
        this.sp = this.node.getComponent(sp.Skeleton);
        if (this.sp == null) {
            console.error("节点上没有发现 sp.Skeleton 组件");
            return;
        }
        
        if (this.animation.length > 0) {
            this.sp.setAnimation(0, this.animation[0].toString(), false);
            for (let i = 1; i < this.animation.length; i++) {
                this.sp.addAnimation(0, this.animation[i].toString(), false);
            }
        }
    }

    count_animation = 0;
    start() {
        if (this.auto_removeSelf == true) { /////////// 如果 播放完 自杀
            Qrj_spine.set_end_listener(this.sp, () => {
                if (++this.count_animation >= this.animation.length) {
                    this.node.removeFromParent();
                }
            });
        }
    }

    // update (dt) {}


    ///////////////////////////// 设置结束动画
    public static set_end_listener(spine: sp.Skeleton | cc.Node, end_listener: Function) {
        if (spine instanceof cc.Node) {
            let s = spine.getComponent(sp.Skeleton);
            if (!s) {
                console.error(`节点${spine.name}上没有发现 sp.Skeleton 组件`);
                return;
            } else {
                spine = s;
            }
        }
        spine.setCompleteListener(() => {
            end_listener && end_listener();
        });
    }

    ////////////////////////// 设置结束动画并移除节点
    public static end_and_removeSelf(spine: sp.Skeleton | cc.Node, end_listener: Function = null) {
        this.set_end_listener(spine, () => {
            if (spine instanceof cc.Node) {
                spine.removeFromParent();
            } else {
                spine.node.removeFromParent();
            }

            end_listener && end_listener();
        });
    }

    ////////////////////////// 播放动画
    public static play_anim(spine: sp.Skeleton | cc.Node, name: string, loop: boolean) {
        if (spine instanceof cc.Node) {
            let s = spine.getComponent(sp.Skeleton);
            if (!s) {
                console.error(`节点${spine.name}上没有发现 sp.Skeleton 组件`);
                return;
            } else {
                spine = s;
            }
        }

        spine.setAnimation(0, name, loop);
    }
}
